package com.hancher.gamelife2.saolei;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.hancher.common.androidutil.AssetUtil;
import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.androidutil.ToastUtil;

import java.util.Map;

/**
 * 作者 : Hancher ytu_shaoweijie@163.com <br/>
 * 时间 : 2021/3/23 13:49 <br/>
 * 描述 : 贡献图
 */
public class SaoLeiView extends View {

    private Map<String, Bitmap> images = null;

    //region init
    public SaoLeiView(Context context) {
        super(context);
        initData(context);
    }

    public SaoLeiView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initData(context);
    }

    public SaoLeiView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initData(context);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public SaoLeiView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initData(context);
    }

    public void initData(Context context) {
        images = AssetUtil.getAllImageMap(context, "saolei");
//        images.forEach((s, bitmap) -> LogUtil.d("key=%s, map=%s",s,bitmap));

        BombControl.prepare(this);
        TimeControl.prepare();

    }
    //endregion


    //region draw
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Paint paint = new Paint();
        int l = getPaddingLeft();
        int r = getWidth() - getPaddingRight();
        int t = getPaddingTop();
        int b = getHeight() - getPaddingBottom();

        //可用布局
        int h = getHeight() - getPaddingTop() - getPaddingBottom();
        int w = getWidth() - getPaddingLeft() - getPaddingRight();

        //人脸
        int fh = getWidth() / 7;
        int fw = getWidth() / 7;

        //时间 & 计时器
        int th = getWidth() * 2 / 21;
        int tw = getWidth() / 7;
        int cp = getWidth() / 5;

        //行间距
        int rp = th / 4;

        //绘制
        canvas.drawColor(Color.GRAY);
        drawFace(canvas, paint, (getWidth() - fw) / 2, t, (getWidth() + fw) / 2, t + fw);
        drawTime(canvas, paint, (getWidth() - cp) / 2 - tw, t + fw + rp, (getWidth() - cp) / 2, t + fw + rp + th);
        drawBoard(canvas, paint, (getWidth() + cp) / 2, t + fw + rp, (getWidth() + cp) / 2 + tw, t + fw + rp + th);
        drawLei(canvas, paint, l, t + fw + rp + th + rp, r, b);
    }

    private int bombL = 0;
    private int bombT = 0;
    private int bombR = 0;
    private int bombB = 0;
    private int bombWH = 0;

    private void drawBoard(Canvas canvas, Paint paint, int l, int t, int r, int b) {
        int w = (r - l) / 3;
        drawBitmapQuick(canvas, paint, String.format("d%d.gif", BombControl.currentBombCount / 100 % 10), l, t, l + w, b);
        drawBitmapQuick(canvas, paint, String.format("d%d.gif", BombControl.currentBombCount / 10 % 10), l + w, t, l + 2 * w, b);
        drawBitmapQuick(canvas, paint, String.format("d%d.gif", BombControl.currentBombCount % 10), l + 2 * w, t, r, b);
    }

    private void drawLeiInner(Canvas canvas, Paint paint, int l, int t, int r, int b) {
        int itemWH = (r - l) / BombControl.MAX_COL;
        bombL = l;
        bombT = t;
        bombR = r;
        bombB = b;
        bombWH = itemWH;
        String bitmapStr;
        for (int i = 0; i < BombControl.MAX_ROW; i++) {//30
            for (int j = 0; j < BombControl.MAX_COL; j++) {//16
                if (BombControl.bombBeans[i][j].getShowState() == BombControl.ShowState.HIDE_EMPTY) {
                    bitmapStr = "blank.gif";
                } else if (BombControl.bombBeans[i][j].getShowState() == BombControl.ShowState.HIDE_FLAG) {
                    bitmapStr = "flag.gif";
                } else if (BombControl.bombBeans[i][j].getShowState() == BombControl.ShowState.HIDE_QUESTION) {
                    bitmapStr = "ask.gif";
                } else if (BombControl.bombBeans[i][j].getShowState() == BombControl.ShowState.SHOW_BOMB_FAIL) {
                    ToastUtil.showErr("失败");
                    bitmapStr = "mine2.gif";
                } else if (BombControl.bombBeans[i][j].getShowState() == BombControl.ShowState.SHOW_EMPTY) {
                    bitmapStr = BombControl.bombBeans[i][j].getShowNumber() + ".gif";
                } else {
                    continue;
                }
                drawBitmapQuick(canvas, paint, bitmapStr, l + j * itemWH, t + i * itemWH, l + itemWH * (j + 1), t + itemWH * (i + 1));
            }
        }
    }

    private void drawLei(Canvas canvas, Paint paint, int l, int t, int r, int b) {
        int w = r - l;
        int h = b - t;
        boolean isWFull = w / h - BombControl.MAX_COL / BombControl.MAX_ROW < 0;
        if (isWFull) {
            int ih = w * BombControl.MAX_ROW / BombControl.MAX_COL;
            drawLeiInner(canvas, paint, l, (h - ih) / 2 + t, r, (h + ih) / 2 + t);
        } else {
            int iw = h * BombControl.MAX_COL / BombControl.MAX_ROW;
            drawLeiInner(canvas, paint, (w - iw) / 2 + l, t, (w + iw) / 2 + l, b);
        }
    }

    private void drawTime(Canvas canvas, Paint paint, int l, int t, int r, int b) {
        int w = (r - l) / 3;
        drawBitmapQuick(canvas, paint, String.format("d%d.gif", TimeControl.currentTimecount / 100 % 10), l, t, l + w, b);
        drawBitmapQuick(canvas, paint, String.format("d%d.gif", TimeControl.currentTimecount / 10 % 10), l + w, t, l + 2 * w, b);
        drawBitmapQuick(canvas, paint, String.format("d%d.gif", TimeControl.currentTimecount % 10), l + 2 * w, t, r, b);
    }

    private void drawFace(Canvas canvas, Paint paint, int l, int t, int r, int b) {
        drawBitmapQuick(canvas, paint, "face0.gif", l, t, r, b);
    }

    private void drawBitmapQuick(Canvas canvas, Paint paint, String bitmapStr, int l, int t, int r, int b) {
        Bitmap face = images.get(bitmapStr);
        if (face == null) {
            LogUtil.d(bitmapStr + " is null");
            return;
        }
        if (face.getWidth() == 0 || face.getHeight() == 0) {
            LogUtil.d(bitmapStr + " w=" + face.getWidth() + ", h=" + face.getHeight());
            return;
        }
        Matrix matrix = new Matrix();
        float scale = (1.0f * (r - l)) / face.getWidth();
        matrix.postScale(scale, scale);
        try {
            Bitmap face2 = Bitmap.createBitmap(face, 0, 0, face.getWidth(), face.getHeight(), matrix, true);
            canvas.drawBitmap(face2, l, t, paint);
        } catch (IllegalArgumentException e) {
            LogUtil.e("image=%s, %f[%d,%d] %s", bitmapStr, scale, face.getWidth(), face.getHeight(), e.getMessage());
        }
    }
    //endregion

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() != MotionEvent.ACTION_UP) {
            return true;
        }
        int col = (int) ((event.getX() - bombL) / bombWH);
        int row = (int) ((event.getY() - bombT) / bombWH);
        if (col < 0 || row < 0 || col > BombControl.MAX_COL - 1 || row > BombControl.MAX_ROW - 1) {
            LogUtil.w("[%d,%d,%d,%d] [%d,%d]", bombL, bombT, bombR, bombB, col, row);
            return true;
        }
        if (BombControl.isPrepare && !TimeControl.isStart) {
            TimeControl.start(this);
            BombControl.isPrepare = false;
        } else if (!TimeControl.isStart) {
            ToastUtil.showErr("请点击重新开始");
            return true;
        }
        boolean isLongPress = event.getEventTime() - event.getDownTime() > 300;
//        LogUtil.o(String.format("click %b[%d,%d] ",isLongPress, row, col), BombControl.bombBeans[row][col]);
        BombControl.click(isLongPress, row, col);
        if (BombControl.isSuccess()) {
            ToastUtil.show("挑战成功");
            TimeControl.stop();
        }
        invalidate();
        return true;
    }

    @Override
    protected void onDetachedFromWindow() {
        TimeControl.stop();
        BombControl.stop();
        super.onDetachedFromWindow();
    }

    public void initRank(int time, int maxCol, int maxRow, int bomb) {
        TimeControl.TIME_COUNT = time;
        BombControl.MAX_COL = maxCol;
        BombControl.MAX_ROW = maxRow;
        BombControl.BOMB_COUNT = bomb;
    }
}
